package org.example.util;

import org.example.common.entity.Discount;

import java.math.BigDecimal;

public class DiscountUtil {

    /**
     * 计算折扣后的价格
     *
     * @param originalPrice 原价
     * @param discount      折扣规则
     * @return 折扣后的价格
     */
    public static BigDecimal calculateDiscount(BigDecimal originalPrice, Discount discount) {
        if (discount == null || discount.getStatus() != 1) {
            return originalPrice; // 无折扣或折扣未启用
        }

        BigDecimal discountedPrice = originalPrice;

        switch (discount.getType()) {
            case 1: // 固定金额折扣
                discountedPrice = originalPrice.subtract(discount.getValue());
                break;
            case 2: // 百分比折扣: 折扣百分比
                discountedPrice = originalPrice.multiply(discount.getValue().divide(BigDecimal.valueOf(100))); // 计算折扣后的价格
                break;
            case 3: // 满减折扣: 满金额减金额
                if (originalPrice.compareTo(discount.getMinAmount()) >= 0) {
                    discountedPrice = originalPrice.subtract(discount.getValue());
                }
                break;
            case 4: // 阶梯折扣: 满金额减金额
                if (originalPrice.compareTo(discount.getMinAmount()) >= 0 &&
                    originalPrice.compareTo(discount.getMaxAmount()) <= 0) {
                    discountedPrice = originalPrice.multiply(discount.getValue().divide(BigDecimal.valueOf(100)));
                }
                break;
            default:
                throw new IllegalArgumentException("未知的折扣类型");
        }

        // 确保折扣后的价格不小于 0
        return discountedPrice.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : discountedPrice;
    }
}